<?php

if (!function_exists('output')) {
    function output($code = 1000, $message = 'success', $data = [], $headers = [], $status = 200)
    {
        $data = [
            'code' => $code,
            'info' => $message,
            'data' => $data,
        ];

        return response($data, $status, $headers);
    }
}

if (!function_exists('error')) {
    function error($code = 1002, $message = 'failed', $data = [], $headers = [], $status = 200)
    {
        $data = [
            'code' => $code,
            'info' => $message,
            'data' => $data,
        ];

        return response($data, $status, $headers);
    }
}

if (!function_exists('get_domain')) {
    /**
     * 获取域名
     *
     * @param string $url 地址
     *
     * @return string
     */
    function get_domain($url = '')
    {
        //获取域名
        if (empty($url)) {
            return isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';
        } else {
            $info = parse_url($url);

            return $info['host'];
        }
    }
}

if (!function_exists('dialog')) {
    /**
     * Log a debug message to the logs.
     *
     * @param  string $message
     * @param  array  $context
     *
     * @return null|\Illuminate\Contracts\Logging\Log
     */
    function dialog($message = null, array $context = [])
    {
        if (is_null($message)) {
            return app('log');
        }
        //var_dump(debug_backtrace());
        //	dd(debugBacktraceInfo());

        $traceInfo = '';
        if (env('APP_DEBUG')) {
            list($file, $line, $func, $class) = debugBacktraceInfo();
            $traceInfo = (!empty($class) ? "$class::" : '') . "$func() $file line: $line";
        }

        return app('log')->debug("message: " . $message . ' getRequestUri：' . request()->getRequestUri() . ' trace: ' . $traceInfo . ' data:', $context);
    }
}

if (!function_exists('dialog_error')) {
    /**
     * Log a debug message to the logs.
     *
     * @param  string $message
     * @param  array  $context
     *
     * @return null|\Illuminate\Contracts\Logging\Log
     */
    function dialog_error($message = null, array $context = [])
    {
        if (is_null($message)) {
            return app('log');
        }

        $traceInfo = '';
        if (env('APP_DEBUG')) {
            list($file, $line, $func, $class) = debugBacktraceInfo();
            $traceInfo = (!empty($class) ? "$class::" : '') . "$func() $file line: $line";
        }
        app('log')->useFiles(storage_path() . "/logs");

        return app('log')->error("message: " . $message . ' getRequestUri：' . request()->getRequestUri() . ' trace: ' . $traceInfo . ' data:', $context);
    }
}

if (!function_exists('debugBacktraceInfo')) {
    function debugBacktraceInfo($depth = 0)
    {
        $bt = debug_backtrace();
        $bt0 = isset($bt[$depth]) ? $bt[$depth] : null;
        $bt1 = isset($bt[$depth + 1]) ? $bt[$depth + 1] : null;

        $class = isset($bt1['class']) ? $bt1['class'] : null;
        if ($class !== null && strcasecmp($class, 'Log_composite') == 0) {
            $depth++;
            $bt0 = isset($bt[$depth]) ? $bt[$depth] : null;
            $bt1 = isset($bt[$depth + 1]) ? $bt[$depth + 1] : null;
            $class = isset($bt1['class']) ? $bt1['class'] : null;
        }

        $file = isset($bt0) ? $bt0['file'] : null;
        $line = isset($bt0) ? $bt0['line'] : 0;
        $func = isset($bt1) ? $bt1['function'] : null;
        $bt2 = isset($bt[$depth + 2]) ? $bt[$depth + 2] : null;
        $file = is_array($bt1) ? $bt1['file'] : null;
        $line = is_array($bt1) ? $bt1['line'] : 0;
        $func = is_array($bt2) ? $bt2['function'] : null;
        $class = isset($bt2['class']) ? $bt2['class'] : null;

        if ($func === null) {
            $func = '(none)';
        }

        return [$file, $line, $func, $class];
    }
}


if (!function_exists('get_sub_domain')) {

    /**
     * 获取子域名
     *
     * @param string $domain 域名
     * @param        $topdomain
     *
     * @return string
     */
    function get_sub_domain($domain, $topdomain)
    {
        $subdomain = str_replace($topdomain, '', $domain);

        return trim($subdomain, '.');
    }
}
/**
 * 获取表单验证错误
 */
if (!function_exists('validatorErrors')) {
    function validatorErrors($validatorErrors)
    {
        $firstError = current(current(current($validatorErrors)));
        $error = $firstError ?: 'Request Parameter error';

        return $error;
    }
}


/**
 * 写入业务日志（单条直接写入）
 * demo:
 * $logs['request'] = $request;
 * $logs['response'] = $response;
 * $logs['line'] = __LINE__;
 * $logs['exception'] = $exception->getMessage();
 * _writeBiz(json_encode($logs), __FUNCTION__, class_basename(__CLASS__));
 *
 * 使用 docker-compose.yml volumes 挂载目录
 *
 * @param string $log  日志内容
 * @param string $name 文件名称
 * @param string $dir  目录名称
 *
 * @return void
 */
function _writeBiz($log, $name = 'info', $dir = '')
{

    //写日志记录 判断日志路径，如果APP_LOG_DIR存在写入，否者写入storage_path()
    if (!defined('DESTINATION_PATH')) {
        $storagePath = storage_path() . '/logs'; // 框架日志目录
        $appLogsPath = env('APP_LOG_DIR', '');  // 全局日志目录（默认使用）


        $envDir = !empty($appLogsPath) && is_dir($appLogsPath) ? $appLogsPath : $storagePath;

 

        $envDir .= defined('ARTISAN_ENV') ? '/artisan' : '/web'; // shell：使用artisan，web：使用web
        $destination = $envDir . "/" . date('Ymd/') . get_domain() . '/'; //日志记录目录

        define('DESTINATION_PATH', $destination);
    }
    $destination = DESTINATION_PATH;
    if (!empty($dir)) {
        $destination .= "{$dir}/";
    }
    //判断是否存在目录分割线
    $destination = substr($destination, -1) == '/' ? $destination : $destination . '/';
    //判断目录是否存在
    if (!is_dir($destination)) mkdir($destination, 0755, true);
    //组织日志名称
    $logs_name = $destination . $name . '.log';

    if (!is_file($logs_name)) {
        touch($logs_name);
        chmod($logs_name, 0775);
    }
    $date = date('Y-m-d H:i:s', time());
    $log = "[{$date}] - {$log}\n";
    error_log($log, 3, $logs_name, '');
}


function _writeBizSuccess($log, $name = 'info', $dir = '')
{
    _writeBiz($log, $name . '_success', $dir);
}


function _writeBizError($log, $name = 'info', $dir = '')
{
    _writeBiz($log, $name . '_error', $dir);
}


function _writeBizException($log, $name = 'info', $dir = '')
{
    _writeBiz($log, $name . '_exception', $dir);
}